package com.zhentao.PollutionPredictio.controller;

import com.zhentao.PollutionPredictio.model.service.IChemicalFactoryService;
import com.zhentao.PollutionPredictio.model.mapper.ChemicalFactoryMapper;
import com.zhentao.PollutionPredictio.service.PollutionPredictionAiService;
import com.zhentao.pojo.ChemicalFactory;
import com.zhentao.util.Enum.ApiServiceExceptionEnum;
import com.zhentao.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 设备污染预测控制器
 * 基于设备位置进行污染预测分析
 */
@RestController
@RequestMapping("/device-pollution-prediction")
@CrossOrigin(origins = "*")
public class DevicePollutionPredictionController {

    @Autowired
    private PollutionPredictionAiService aiService;

    @Autowired
    @Qualifier("chemicalFactoryServiceImpl")
    private IChemicalFactoryService chemicalFactoryService;

    @Autowired
    private ChemicalFactoryMapper chemicalFactoryMapper;

    /**
     * 测试接口 - 验证服务是否正常
     * GET /device-pollution-prediction/test
     */
    @GetMapping("/test")
    public ResultVo test() {
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "设备污染预测服务正常运行");
            result.put("timestamp", System.currentTimeMillis());
            result.put("service", "DevicePollutionPredictionController");
            
            return ResultVo.success(result);
        } catch (Exception e) {
            System.err.println("测试接口失败: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 基于设备位置的污染预测分析
     * POST /device-pollution-prediction/analyze-by-location
     */
    @PostMapping("/analyze-by-location")
    public ResultVo analyzeByLocation(@RequestBody Map<String, Object> requestData) {
        try {
            System.out.println("开始基于设备位置的污染预测分析");
            System.out.println("请求数据: " + requestData);

            // 获取设备位置数据
            Map<String, Object> locationData = (Map<String, Object>) requestData.get("locationData");
            if (locationData == null) {
                return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
            }

            // 提取设备信息
            String deviceId = getStringValue(locationData.get("deviceId")); // 安全转换
            String deviceName = getStringValue(locationData.get("deviceName"));
            Double latitude = getDoubleValue(locationData.get("latitude"));
            Double longitude = getDoubleValue(locationData.get("longitude"));
            Map<String, Object> currentData = (Map<String, Object>) locationData.get("currentData");
            
            System.out.println("设备信息提取完成:");
            System.out.println("  deviceId: " + deviceId);
            System.out.println("  deviceName: " + deviceName);
            System.out.println("  latitude: " + latitude);
            System.out.println("  longitude: " + longitude);
            System.out.println("  currentData: " + currentData);

            // 查找附近的化工厂
            List<Map<String, Object>> nearbyFactories = findNearbyFactories(latitude, longitude);

            // 检测污染状态
            boolean isPolluted = detectPollution(currentData);
            
            // 分析污染源
            Map<String, Object> pollutionSourceAnalysis = analyzePollutionSource(currentData, nearbyFactories, latitude, longitude);
            
            // 生成分析结果（智能降级机制）
            String predictionResult;
            boolean useAIService = true; // 默认使用AI服务

            // 检查前端是否传入了AI服务开关
            Object useAIServiceObj = requestData.get("useAIService");
            if (useAIServiceObj instanceof Boolean) {
                useAIService = (Boolean) useAIServiceObj;
            }

            if (useAIService) {
                try {
                    predictionResult = generateAIAnalysis(deviceName, latitude, longitude, currentData, nearbyFactories, pollutionSourceAnalysis);
                    System.out.println("AI分析成功完成");
                } catch (Exception e) {
                    System.err.println("AI分析失败，使用规则分析降级: " + e.getMessage());
                    predictionResult = generateLocationBasedPrediction(deviceName, latitude, longitude, currentData, nearbyFactories, pollutionSourceAnalysis);
                }
            } else {
                // 直接使用规则分析
                System.out.println("使用规则分析（AI服务已禁用）");
                predictionResult = generateLocationBasedPrediction(deviceName, latitude, longitude, currentData, nearbyFactories, pollutionSourceAnalysis);
            }

            // 生成建议措施
            List<String> recommendations = generateRecommendations(currentData, nearbyFactories, pollutionSourceAnalysis);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("deviceId", deviceId);
            result.put("deviceName", deviceName);
            result.put("latitude", latitude);
            result.put("longitude", longitude);
            result.put("nearbyFactories", nearbyFactories);
            result.put("isPolluted", isPolluted);
            result.put("pollutionSourceAnalysis", pollutionSourceAnalysis);
            result.put("prediction", predictionResult);
            result.put("recommendations", recommendations);
            result.put("timestamp", System.currentTimeMillis());

            System.out.println("设备污染预测分析完成");
            return ResultVo.success(result);

        } catch (Exception e) {
            System.err.println("设备污染预测分析失败: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 查找附近的化工厂
     */
    private List<Map<String, Object>> findNearbyFactories(Double deviceLat, Double deviceLng) {
        List<Map<String, Object>> nearbyFactories = new ArrayList<>();

        try {
            // 获取所有化工厂数据
            List<ChemicalFactory> allFactories = chemicalFactoryService.findAllFactory();
            
            for (ChemicalFactory factory : allFactories) {
                if (factory.getLatitude() != null && factory.getLongitude() != null) {
                    // 计算距离
                    double distance = calculateDistance(
                        deviceLat, deviceLng,
                        factory.getLatitude().doubleValue(), 
                        factory.getLongitude().doubleValue()
                    );

                    // 只考虑10公里范围内的工厂
                    if (distance <= 10.0) {
                        Map<String, Object> factoryInfo = new HashMap<>();
                        factoryInfo.put("id", factory.getFactoryId());
                        factoryInfo.put("name", factory.getFactoryName());
                        factoryInfo.put("latitude", factory.getLatitude());
                        factoryInfo.put("longitude", factory.getLongitude());
                        factoryInfo.put("industry", factory.getFactoryType());
                        factoryInfo.put("mainPollutants", factory.getMainPollutants());
                        factoryInfo.put("distance", Math.round(distance * 10.0) / 10.0); // 保留一位小数
                        
                        // 根据距离和风险等级确定风险级别
                        String riskLevel = determineRiskLevel(distance, factory.getRiskLevel());
                        factoryInfo.put("riskLevel", riskLevel);
                        
                        nearbyFactories.add(factoryInfo);
                    }
                }
            }

            // 按距离排序
            nearbyFactories.sort((a, b) -> {
                Double distA = (Double) a.get("distance");
                Double distB = (Double) b.get("distance");
                return distA.compareTo(distB);
            });

            System.out.println("找到附近化工厂数量: " + nearbyFactories.size());
            
        } catch (Exception e) {
            System.err.println("查找附近化工厂失败: " + e.getMessage());
            e.printStackTrace();
        }

        return nearbyFactories;
    }

    /**
     * 检测是否存在污染
     */
    private boolean detectPollution(Map<String, Object> currentData) {
        if (currentData == null) return false;
        
        Object ph = currentData.get("ph");
        Object temp = currentData.get("temp");
        Object ntu = currentData.get("ntu");
        String status = getStringValue(currentData.get("status"));
        
        // 设备故障也算污染风险
        if ("fault".equals(status)) return true;
        
        // 检查各项指标是否异常
        if (ph != null) {
            double phValue = getDoubleValue(ph);
            if (phValue < 6.0 || phValue > 9.0) return true; // pH严重异常
        }
        
        if (temp != null) {
            double tempValue = getDoubleValue(temp);
            if (tempValue < 15 || tempValue > 35) return true; // 温度严重异常
        }
        
        if (ntu != null) {
            double ntuValue = getDoubleValue(ntu);
            if (ntuValue > 5000) return true; // 浊度严重异常
        }
        
        return false;
    }
    
    /**
     * 分析污染源
     */
    private Map<String, Object> analyzePollutionSource(Map<String, Object> currentData, 
                                                      List<Map<String, Object>> nearbyFactories, 
                                                      Double latitude, Double longitude) {
        Map<String, Object> analysis = new HashMap<>();
        
        // 检测污染状态
        boolean isPolluted = detectPollution(currentData);
        analysis.put("isPolluted", isPolluted);
        
        if (!isPolluted) {
            analysis.put("message", "当前水质正常，未检测到污染");
            analysis.put("suspectedFactories", new ArrayList<>());
            return analysis;
        }
        
        // 分析可能的污染源
        List<Map<String, Object>> suspectedFactories = new ArrayList<>();
        
        for (Map<String, Object> factory : nearbyFactories) {
            Double distance = (Double) factory.get("distance");
            String riskLevel = (String) factory.get("riskLevel");
            String industry = (String) factory.get("industry");
            String pollutants = (String) factory.get("mainPollutants");
            
            // 计算污染可能性评分
            int pollutionScore = calculatePollutionScore(currentData, factory, distance);
            
            if (pollutionScore > 0) {
                Map<String, Object> suspectedFactory = new HashMap<>();
                suspectedFactory.put("factoryId", factory.get("id"));
                suspectedFactory.put("factoryName", factory.get("name"));
                suspectedFactory.put("distance", distance);
                suspectedFactory.put("riskLevel", riskLevel);
                suspectedFactory.put("industry", industry);
                suspectedFactory.put("mainPollutants", pollutants);
                suspectedFactory.put("pollutionScore", pollutionScore);
                suspectedFactory.put("pollutionProbability", Math.min(pollutionScore * 10, 100)); // 转换为百分比
                suspectedFactory.put("reason", generatePollutionReason(currentData, factory, distance));
                
                suspectedFactories.add(suspectedFactory);
            }
        }
        
        // 按污染评分排序
        suspectedFactories.sort((a, b) -> {
            Integer scoreA = (Integer) a.get("pollutionScore");
            Integer scoreB = (Integer) b.get("pollutionScore");
            return scoreB.compareTo(scoreA);
        });
        
        analysis.put("suspectedFactories", suspectedFactories);
        
        // 确定最可能的污染源
        if (!suspectedFactories.isEmpty()) {
            Map<String, Object> primarySuspect = suspectedFactories.get(0);
            analysis.put("primarySuspect", primarySuspect);
            analysis.put("primarySuspectName", primarySuspect.get("factoryName"));
            analysis.put("primarySuspectProbability", primarySuspect.get("pollutionProbability"));
        } else {
            analysis.put("primarySuspect", null);
            analysis.put("primarySuspectName", "未知");
            analysis.put("primarySuspectProbability", 0);
        }
        
        return analysis;
    }
    
    /**
     * 计算污染评分
     */
    private int calculatePollutionScore(Map<String, Object> currentData, Map<String, Object> factory, Double distance) {
        int score = 0;
        
        // 距离因素（距离越近，污染可能性越高）
        if (distance <= 1.0) score += 30;
        else if (distance <= 3.0) score += 20;
        else if (distance <= 5.0) score += 10;
        else if (distance <= 10.0) score += 5;
        
        // 风险等级因素
        String riskLevel = (String) factory.get("riskLevel");
        if ("high".equals(riskLevel)) score += 25;
        else if ("medium".equals(riskLevel)) score += 15;
        else score += 5;
        
        // 污染物匹配因素
        String pollutants = (String) factory.get("mainPollutants");
        if (pollutants != null) {
            // 根据当前数据异常情况匹配污染物
            Object ph = currentData.get("ph");
            Object ntu = currentData.get("ntu");
            Object temp = currentData.get("temp");
            
            if (ph != null) {
                double phValue = getDoubleValue(ph);
                if (phValue < 6.0 || phValue > 9.0) {
                    if (pollutants.contains("酸") || pollutants.contains("碱")) score += 20;
                }
            }
            
            if (ntu != null) {
                double ntuValue = getDoubleValue(ntu);
                if (ntuValue > 3000) {
                    if (pollutants.contains("悬浮物") || pollutants.contains("颗粒物")) score += 15;
                }
            }
            
            if (temp != null) {
                double tempValue = getDoubleValue(temp);
                if (tempValue > 30) {
                    if (pollutants.contains("热") || pollutants.contains("温度")) score += 10;
                }
            }
        }
        
        return score;
    }
    
    /**
     * 生成污染原因说明
     */
    private String generatePollutionReason(Map<String, Object> currentData, Map<String, Object> factory, Double distance) {
        StringBuilder reason = new StringBuilder();
        
        String factoryName = (String) factory.get("factoryName");
        String riskLevel = (String) factory.get("riskLevel");
        
        reason.append("可能原因：");
        
        // 距离因素
        if (distance <= 2.0) {
            reason.append("距离极近(").append(distance).append("km)，");
        } else if (distance <= 5.0) {
            reason.append("距离较近(").append(distance).append("km)，");
        }
        
        // 风险等级
        if ("high".equals(riskLevel)) {
            reason.append("高风险工厂，");
        } else if ("medium".equals(riskLevel)) {
            reason.append("中等风险工厂，");
        }
        
        // 污染物匹配
        Object ph = currentData.get("ph");
        Object ntu = currentData.get("ntu");
        
        if (ph != null) {
            double phValue = getDoubleValue(ph);
            if (phValue < 6.0 || phValue > 9.0) {
                reason.append("pH异常可能与工厂排放的酸碱物质相关");
            }
        } else if (ntu != null) {
            double ntuValue = getDoubleValue(ntu);
            if (ntuValue > 3000) {
                reason.append("浊度异常可能与工厂排放的悬浮物相关");
            }
        } else {
            reason.append("污染物类型匹配");
        }
        
        return reason.toString();
    }

    /**
     * 调用AI服务进行污染预测分析
     */
    private String generateAIAnalysis(String deviceName, Double latitude, Double longitude,
                                     Map<String, Object> currentData, List<Map<String, Object>> nearbyFactories,
                                     Map<String, Object> pollutionSourceAnalysis) {
        try {
            System.out.println("开始调用AI服务进行污染预测分析...");

            // 构建AI分析提示词
            String aiPrompt = buildAIAnalysisPrompt(deviceName, latitude, longitude, currentData, nearbyFactories, pollutionSourceAnalysis);

            // 调用AI服务
            Map<String, Object> aiParameters = new HashMap<>();
            aiParameters.put("prompt", aiPrompt);
            aiParameters.put("deviceName", deviceName);
            aiParameters.put("latitude", latitude);
            aiParameters.put("longitude", longitude);
            aiParameters.put("currentData", currentData);
            aiParameters.put("nearbyFactories", nearbyFactories);
            aiParameters.put("pollutionSourceAnalysis", pollutionSourceAnalysis);

            String aiResult = aiService.generalAnalysis("pollution_trend_prediction", aiParameters);

            System.out.println("AI分析完成，原始结果长度: " + (aiResult != null ? aiResult.length() : 0));

            // 如果AI服务失败，使用备用的规则分析
            if (aiResult == null || aiResult.trim().isEmpty()) {
                System.out.println("AI服务返回空结果，使用备用分析方法");
                return generateLocationBasedPrediction(deviceName, latitude, longitude, currentData, nearbyFactories, pollutionSourceAnalysis);
            }

            return aiResult;

        } catch (Exception e) {
            System.err.println("调用AI服务失败: " + e.getMessage());
            e.printStackTrace();

            // AI服务失败时，使用备用方法
            System.out.println("使用备用分析方法");
            return generateLocationBasedPrediction(deviceName, latitude, longitude, currentData, nearbyFactories, pollutionSourceAnalysis);
        }
    }

    /**
     * 构建AI分析提示词
     */
    private String buildAIAnalysisPrompt(String deviceName, Double latitude, Double longitude,
                                        Map<String, Object> currentData, List<Map<String, Object>> nearbyFactories,
                                        Map<String, Object> pollutionSourceAnalysis) {

        StringBuilder prompt = new StringBuilder();
        prompt.append("请作为水污染预测专家，基于以下信息进行专业分析：\n\n");

        // 设备信息
        prompt.append("监测设备信息：\n");
        prompt.append("- 设备名称：").append(deviceName).append("\n");
        prompt.append("- 地理位置：").append(latitude).append(", ").append(longitude).append("\n");

        // 当前监测数据
        if (currentData != null) {
            prompt.append("\n当前水质监测数据：\n");
            Object ph = currentData.get("ph");
            Object temp = currentData.get("temp");
            Object ntu = currentData.get("ntu");
            String status = getStringValue(currentData.get("status"));

            if (ph != null) prompt.append("- pH值：").append(ph).append("\n");
            if (temp != null) prompt.append("- 水温：").append(temp).append("°C\n");
            if (ntu != null) prompt.append("- 浊度：").append(ntu).append(" NTU\n");
            if (status != null) prompt.append("- 设备状态：").append(status).append("\n");
        }

        // 污染检测结果
        boolean isPolluted = (Boolean) pollutionSourceAnalysis.get("isPolluted");
        prompt.append("\n污染检测结果：").append(isPolluted ? "检测到污染" : "水质正常").append("\n");

        // 附近化工厂信息
        if (nearbyFactories != null && !nearbyFactories.isEmpty()) {
            prompt.append("\n周边化工厂信息（10公里范围内）：\n");
            for (Map<String, Object> factory : nearbyFactories) {
                String name = (String) factory.get("name");
                Double distance = (Double) factory.get("distance");
                String industry = (String) factory.get("industry");
                String riskLevel = (String) factory.get("riskLevel");

                prompt.append("- ").append(name).append("（距离：").append(distance).append("km，行业：").append(industry).append("，风险等级：").append(riskLevel).append("）\n");
            }
        } else {
            prompt.append("\n周边化工厂信息：10公里范围内未发现化工厂\n");
        }

        // 污染源分析结果
        if (isPolluted) {
            String primarySuspectName = (String) pollutionSourceAnalysis.get("primarySuspectName");
            if (!"未知".equals(primarySuspectName)) {
                prompt.append("\n初步分析结果：\n");
                prompt.append("- 最可能的污染源：").append(primarySuspectName).append("\n");
                Object probability = pollutionSourceAnalysis.get("primarySuspectProbability");
                if (probability != null) {
                    prompt.append("- 污染可能性：").append(probability).append("%\n");
                }
            }
        }

        // AI分析要求
        prompt.append("\n请提供以下分析：\n");
        prompt.append("1. 水质状况综合评估（正常/轻度污染/中度污染/重度污染）\n");
        prompt.append("2. 污染原因分析（如果有污染）\n");
        prompt.append("3. 可能的污染源识别\n");
        prompt.append("4. 污染扩散趋势预测\n");
        prompt.append("5. 应急响应建议\n");
        prompt.append("6. 长期监测建议\n\n");

        prompt.append("请用专业、严谨的语言进行分析，格式要清晰易读。");

        System.out.println("构建的AI分析提示词长度: " + prompt.length());
        return prompt.toString();
    }

    /**
     * 生成基于位置的污染预测（备用方法，当AI服务不可用时使用）
     */
    private String generateLocationBasedPrediction(String deviceName, Double latitude, Double longitude,
                                                  Map<String, Object> currentData, List<Map<String, Object>> nearbyFactories,
                                                  Map<String, Object> pollutionSourceAnalysis) {
        
        StringBuilder prediction = new StringBuilder();
        prediction.append("=== 基于设备位置的污染预测分析 ===\n\n");
        prediction.append("监测设备：").append(deviceName).append("\n");
        prediction.append("设备坐标：").append(latitude).append(", ").append(longitude).append("\n\n");

        // 污染状态检测
        boolean isPolluted = (Boolean) pollutionSourceAnalysis.get("isPolluted");
        if (isPolluted) {
            prediction.append("🚨 污染检测结果：检测到污染！\n\n");
        } else {
            prediction.append("✅ 污染检测结果：水质正常\n\n");
        }

        // 分析当前监测数据
        if (currentData != null) {
            prediction.append("当前监测数据：\n");
            Object ph = currentData.get("ph");
            Object temp = currentData.get("temp");
            Object ntu = currentData.get("ntu");
            String status = getStringValue(currentData.get("status"));

            if (ph != null) prediction.append("- pH值：").append(ph).append("\n");
            if (temp != null) prediction.append("- 温度：").append(temp).append("°C\n");
            if (ntu != null) prediction.append("- 浊度：").append(ntu).append(" NTU\n");
            if (status != null) prediction.append("- 设备状态：").append(status).append("\n");

            // 数据异常分析
            boolean hasAbnormalData = false;
            if (ph != null) {
                double phValue = getDoubleValue(ph);
                if (phValue < 6.5 || phValue > 8.5) {
                    hasAbnormalData = true;
                    prediction.append("⚠️ pH值异常，超出正常范围(6.5-8.5)\n");
                }
            }
            if (temp != null) {
                double tempValue = getDoubleValue(temp);
                if (tempValue < 20 || tempValue > 30) {
                    hasAbnormalData = true;
                    prediction.append("⚠️ 温度异常，超出正常范围(20-30°C)\n");
                }
            }
            if (ntu != null) {
                double ntuValue = getDoubleValue(ntu);
                if (ntuValue > 3000) {
                    hasAbnormalData = true;
                    prediction.append("⚠️ 浊度异常，超出正常范围(>3000 NTU)\n");
                }
            }

            if (hasAbnormalData) {
                prediction.append("\n🚨 检测到异常数据，可能存在污染风险！\n");
            } else {
                prediction.append("\n✅ 当前监测数据正常\n");
            }
        }

        // 污染源分析结果
        if (isPolluted) {
            prediction.append("\n=== 污染源分析 ===\n");
            
            String primarySuspectName = (String) pollutionSourceAnalysis.get("primarySuspectName");
            Object primarySuspectProbability = pollutionSourceAnalysis.get("primarySuspectProbability");
            
            if (!"未知".equals(primarySuspectName)) {
                prediction.append("🎯 最可能的污染源：").append(primarySuspectName).append("\n");
                prediction.append("   污染可能性：").append(primarySuspectProbability).append("%\n\n");
                
                // 显示所有可疑工厂
                List<Map<String, Object>> suspectedFactories = (List<Map<String, Object>>) pollutionSourceAnalysis.get("suspectedFactories");
                if (suspectedFactories != null && !suspectedFactories.isEmpty()) {
                    prediction.append("可疑污染源列表：\n");
                    for (int i = 0; i < suspectedFactories.size(); i++) {
                        Map<String, Object> factory = suspectedFactories.get(i);
                        String name = (String) factory.get("factoryName");
                        Double distance = (Double) factory.get("distance");
                        Object probability = factory.get("pollutionProbability");
                        String reason = (String) factory.get("reason");
                        
                        prediction.append((i + 1)).append(". ").append(name).append("\n");
                        prediction.append("   距离：").append(distance).append("km\n");
                        prediction.append("   可能性：").append(probability).append("%\n");
                        prediction.append("   ").append(reason).append("\n\n");
                    }
                }
            } else {
                prediction.append("❓ 未找到明确的污染源，可能是：\n");
                prediction.append("   - 远距离污染源\n");
                prediction.append("   - 临时性污染事件\n");
                prediction.append("   - 自然因素影响\n");
                prediction.append("   - 需要进一步调查\n\n");
            }
        }

        // 分析附近化工厂影响
        if (!nearbyFactories.isEmpty()) {
            prediction.append("\n=== 附近化工厂影响分析 ===\n");
            prediction.append("发现 ").append(nearbyFactories.size()).append(" 家化工厂在10公里范围内：\n\n");

            for (Map<String, Object> factory : nearbyFactories) {
                String name = (String) factory.get("name");
                Double distance = (Double) factory.get("distance");
                String industry = (String) factory.get("industry");
                String pollutants = (String) factory.get("mainPollutants");
                String riskLevel = (String) factory.get("riskLevel");

                prediction.append("🏭 ").append(name).append("\n");
                prediction.append("   距离：").append(distance).append("公里\n");
                prediction.append("   行业：").append(industry).append("\n");
                prediction.append("   主要污染物：").append(pollutants).append("\n");
                prediction.append("   风险等级：").append(riskLevel).append("\n");

                // 根据距离和风险等级给出影响评估
                if (distance <= 2.0) {
                    prediction.append("   ⚠️ 近距离高风险，可能对水质造成直接影响\n");
                } else if (distance <= 5.0) {
                    prediction.append("   ⚠️ 中等距离，需要持续监测\n");
                } else {
                    prediction.append("   ✅ 距离较远，影响相对较小\n");
                }
                prediction.append("\n");
            }

            // 综合风险评估
            prediction.append("=== 综合风险评估 ===\n");
            long highRiskCount = nearbyFactories.stream()
                .filter(f -> "high".equals(f.get("riskLevel")))
                .count();
            long mediumRiskCount = nearbyFactories.stream()
                .filter(f -> "medium".equals(f.get("riskLevel")))
                .count();

            if (highRiskCount > 0) {
                prediction.append("🚨 高风险：发现 ").append(highRiskCount).append(" 家高风险化工厂\n");
                prediction.append("   建议立即加强监测，启动应急预案\n");
            } else if (mediumRiskCount > 0) {
                prediction.append("⚠️ 中等风险：发现 ").append(mediumRiskCount).append(" 家中等风险化工厂\n");
                prediction.append("   建议增加监测频率，密切关注污染指标变化\n");
            } else {
                prediction.append("✅ 低风险：附近化工厂风险等级较低\n");
                prediction.append("   建议保持常规监测即可\n");
            }
        } else {
            prediction.append("\n=== 附近化工厂分析 ===\n");
            prediction.append("✅ 10公里范围内未发现化工厂\n");
            prediction.append("   当前区域相对安全，污染风险较低\n");
        }

        prediction.append("\n=== 预测结论 ===\n");
        if (!nearbyFactories.isEmpty()) {
            prediction.append("基于设备位置和附近化工厂分布，该区域存在一定的污染风险。\n");
            prediction.append("建议加强水质监测，重点关注pH值、浊度等关键指标的变化趋势。\n");
        } else {
            prediction.append("该区域相对安全，污染风险较低，建议保持常规监测。\n");
        }

        return prediction.toString();
    }

    /**
     * 生成建议措施
     */
    private List<String> generateRecommendations(Map<String, Object> currentData, List<Map<String, Object>> nearbyFactories, Map<String, Object> pollutionSourceAnalysis) {
        List<String> recommendations = new ArrayList<>();
        
        // 检查是否检测到污染
        boolean isPolluted = (Boolean) pollutionSourceAnalysis.get("isPolluted");
        
        if (isPolluted) {
            // 污染情况下的紧急建议
            recommendations.add("🚨 立即启动污染应急预案，组织应急响应");
            recommendations.add("📞 立即通知环保部门和相关管理部门");
            recommendations.add("🔍 对可疑污染源进行现场核查");
            
            // 基于污染源分析的建议
            String primarySuspectName = (String) pollutionSourceAnalysis.get("primarySuspectName");
            if (!"未知".equals(primarySuspectName)) {
                recommendations.add("🎯 重点调查" + primarySuspectName + "的排放情况");
                recommendations.add("📋 要求" + primarySuspectName + "提供近期排放监测数据");
            }
            
            List<Map<String, Object>> suspectedFactories = (List<Map<String, Object>>) pollutionSourceAnalysis.get("suspectedFactories");
            if (suspectedFactories != null && !suspectedFactories.isEmpty()) {
                recommendations.add("📊 对所有可疑工厂进行同步监测");
                recommendations.add("🔬 采集水样进行污染物成分分析");
            }
            
            recommendations.add("⏰ 增加监测频率至每5分钟一次");
            recommendations.add("📢 发布污染预警信息，提醒周边居民");
            
        } else {
            // 正常情况下的常规建议
            if (currentData != null) {
                String status = getStringValue(currentData.get("status"));
                if ("fault".equals(status)) {
                    recommendations.add("设备故障，建议立即检修设备，确保监测数据准确性");
                }
                
                Object ph = currentData.get("ph");
                Object ntu = currentData.get("ntu");
                if (ph != null || ntu != null) {
                    recommendations.add("增加监测频率，建议每15分钟采集一次数据");
                }
            }
            
            // 基于附近化工厂的建议
            if (!nearbyFactories.isEmpty()) {
                recommendations.add("建立与附近化工厂的沟通机制，及时了解排放情况");
                recommendations.add("制定针对性的应急预案，提高突发污染事件应对能力");
                
                long highRiskCount = nearbyFactories.stream()
                    .filter(f -> "high".equals(f.get("riskLevel")))
                    .count();
                
                if (highRiskCount > 0) {
                    recommendations.add("启动重点监管模式，对高风险化工厂进行重点监控");
                    recommendations.add("建议环保部门进行现场核查，确保污染治理设施正常运行");
                }
            }
            
            // 通用建议
            recommendations.add("建立水质监测预警系统，实现实时监控和自动报警");
            recommendations.add("定期发布水质监测报告，提高公众环保意识");
            recommendations.add("加强与相关部门的协调配合，形成联防联控机制");
        }

        return recommendations;
    }

    /**
     * 计算两点间距离（公里）
     */
    private double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        final int R = 6371; // 地球半径（公里）
        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);
        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return R * c;
    }

    /**
     * 确定风险等级
     */
    private String determineRiskLevel(double distance, Integer factoryRiskLevel) {
        if (factoryRiskLevel == null) {
            factoryRiskLevel = 2; // 默认中等风险
        }

        // 综合考虑距离和工厂风险等级
        if (distance <= 2.0 && factoryRiskLevel >= 3) {
            return "high";
        } else if (distance <= 5.0 && factoryRiskLevel >= 2) {
            return "medium";
        } else {
            return "low";
        }
    }

    /**
     * 获取设备附近的化工厂列表（用于地图标记）
     * GET /device-pollution-prediction/nearby-factories
     */
    @GetMapping("/nearby-factories")
    public ResultVo getNearbyFactories(@RequestParam double latitude, @RequestParam double longitude, 
                                     @RequestParam(defaultValue = "10") double radius) {
        try {
            List<Map<String, Object>> nearbyFactories = findNearbyFactories(latitude, longitude);
            
            // 过滤指定半径内的工厂
            List<Map<String, Object>> filteredFactories = new ArrayList<>();
            for (Map<String, Object> factory : nearbyFactories) {
                Double distance = (Double) factory.get("distance");
                if (distance <= radius) {
                    filteredFactories.add(factory);
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("deviceLocation", Map.of("latitude", latitude, "longitude", longitude));
            result.put("searchRadius", radius);
            result.put("factories", filteredFactories);
            result.put("count", filteredFactories.size());

            return ResultVo.success(result);
        } catch (Exception e) {
            System.err.println("获取附近化工厂失败: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 批量分析多个设备的污染风险
     * POST /device-pollution-prediction/batch-analyze
     */
    @PostMapping("/batch-analyze")
    public ResultVo batchAnalyze(@RequestBody Map<String, Object> requestData) {
        try {
            System.out.println("开始批量设备污染分析");
            
            List<Map<String, Object>> devices = (List<Map<String, Object>>) requestData.get("devices");
            if (devices == null || devices.isEmpty()) {
                return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
            }

            List<Map<String, Object>> analysisResults = new ArrayList<>();
            
            for (Map<String, Object> device : devices) {
                Map<String, Object> deviceAnalysis = new HashMap<>();
                deviceAnalysis.put("deviceId", device.get("id"));
                deviceAnalysis.put("deviceName", device.get("name"));
                
                Double latitude = getDoubleValue(device.get("latitude"));
                Double longitude = getDoubleValue(device.get("longitude"));
                
                // 查找附近化工厂
                List<Map<String, Object>> nearbyFactories = findNearbyFactories(latitude, longitude);
                deviceAnalysis.put("nearbyFactories", nearbyFactories);
                
                // 计算风险评分
                int riskScore = calculateRiskScore(nearbyFactories);
                deviceAnalysis.put("riskScore", riskScore);
                deviceAnalysis.put("riskLevel", getRiskLevelFromScore(riskScore));
                
                analysisResults.add(deviceAnalysis);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("devices", analysisResults);
            result.put("totalDevices", devices.size());
            result.put("timestamp", System.currentTimeMillis());

            return ResultVo.success(result);
        } catch (Exception e) {
            System.err.println("批量设备分析失败: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 计算风险评分
     */
    private int calculateRiskScore(List<Map<String, Object>> nearbyFactories) {
        int score = 0;
        
        for (Map<String, Object> factory : nearbyFactories) {
            Double distance = (Double) factory.get("distance");
            String riskLevel = (String) factory.get("riskLevel");
            
            // 根据距离和风险等级计算分数
            if (distance <= 2.0) {
                score += "high".equals(riskLevel) ? 10 : "medium".equals(riskLevel) ? 7 : 5;
            } else if (distance <= 5.0) {
                score += "high".equals(riskLevel) ? 7 : "medium".equals(riskLevel) ? 5 : 3;
            } else {
                score += "high".equals(riskLevel) ? 5 : "medium".equals(riskLevel) ? 3 : 1;
            }
        }
        
        return score;
    }

    /**
     * 根据评分确定风险等级
     */
    private String getRiskLevelFromScore(int score) {
        if (score >= 20) return "high";
        else if (score >= 10) return "medium";
        else return "low";
    }

    /**
     * 安全地转换数值类型
     */
    private double getDoubleValue(Object value) {
        if (value == null) return 0.0;
        if (value instanceof Double) return (Double) value;
        if (value instanceof BigDecimal) return ((BigDecimal) value).doubleValue();
        if (value instanceof Number) return ((Number) value).doubleValue();
        try {
            return Double.parseDouble(value.toString());
        } catch (Exception e) {
            return 0.0;
        }
    }

    /**
     * 安全地转换为字符串
     */
    private String getStringValue(Object value) {
        if (value == null) return null;
        return String.valueOf(value);
    }

    /**
     * 根据设备经纬度分析附近的化工厂 - 调用AI服务
     * POST /device-pollution-prediction/analyze-nearby-factories
     */
    @PostMapping("/analyze-nearby-factories")
    public ResultVo analyzeNearbyFactories(@RequestBody Map<String, Object> requestData) {
        try {
            System.out.println("开始根据设备经纬度分析附近的化工厂");
            System.out.println("请求数据: " + requestData);

            // 获取设备经纬度
            Double latitude = getDoubleValue(requestData.get("latitude"));
            Double longitude = getDoubleValue(requestData.get("longitude"));
            Long deviceId = null;

            // 尝试获取设备ID（如果提供的话）
            Object deviceIdObj = requestData.get("deviceId");
            if (deviceIdObj != null) {
                deviceId = Long.valueOf(deviceIdObj.toString());
            }

            if (latitude == 0.0 || longitude == 0.0) {
                return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
            }

            // 查找附近的化工厂
            List<Map<String, Object>> nearbyFactories = findNearbyFactories(latitude, longitude);

            if (nearbyFactories.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("deviceLocation", Map.of("latitude", latitude, "longitude", longitude));
                result.put("nearbyFactories", new ArrayList<>());
                result.put("aiAnalysis", "该区域10公里范围内未发现化工厂，无污染风险。");
                result.put("message", "区域安全，未发现化工厂");
                result.put("timestamp", System.currentTimeMillis());
                return ResultVo.success(result);
            }

            // 调用AI服务进行分析
            String aiAnalysis = callAIAnalysisForFactories(nearbyFactories, latitude, longitude, deviceId);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("deviceLocation", Map.of("latitude", latitude, "longitude", longitude));
            result.put("deviceId", deviceId);
            result.put("nearbyFactories", nearbyFactories);
            result.put("factoryCount", nearbyFactories.size());
            result.put("aiAnalysis", aiAnalysis);
            result.put("timestamp", System.currentTimeMillis());

            System.out.println("化工厂分析完成，发现 " + nearbyFactories.size() + " 家化工厂");
            return ResultVo.success(result);

        } catch (Exception e) {
            System.err.println("化工厂分析失败: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 调用AI服务分析化工厂
     */
    private String callAIAnalysisForFactories(List<Map<String, Object>> nearbyFactories, Double latitude, Double longitude, Long deviceId) {
        try {
            System.out.println("开始调用AI服务分析化工厂...");

            // 构建AI分析提示词
            StringBuilder prompt = new StringBuilder();
            prompt.append("请作为环境污染专家，分析以下化工厂对周边环境的影响：\n\n");

            // 添加设备位置信息
            prompt.append("监测设备位置：").append(latitude).append(", ").append(longitude).append("\n");
            if (deviceId != null) {
                prompt.append("设备ID：").append(deviceId).append("\n");
            }
            prompt.append("\n");

            // 添加化工厂信息
            prompt.append("周边化工厂信息（10公里范围内）：\n");
            for (int i = 0; i < nearbyFactories.size(); i++) {
                Map<String, Object> factory = nearbyFactories.get(i);
                prompt.append((i + 1)).append(". ").append(factory.get("name")).append("\n");
                prompt.append("   距离：").append(factory.get("distance")).append("km\n");
                prompt.append("   行业：").append(factory.get("industry")).append("\n");
                prompt.append("   主要污染物：").append(factory.get("mainPollutants")).append("\n");
                prompt.append("   风险等级：").append(factory.get("riskLevel")).append("\n\n");
            }

            // AI分析要求
            prompt.append("请提供以下专业分析：\n");
            prompt.append("1. 各化工厂的污染风险评估（高风险/中等风险/低风险）\n");
            prompt.append("2. 污染物扩散可能性分析\n");
            prompt.append("3. 对周边水体和居民的影响评估\n");
            prompt.append("4. 优先监测建议\n");
            prompt.append("5. 应急响应措施建议\n");
            prompt.append("6. 长期环境监测规划\n\n");

            prompt.append("请用专业的环境科学语言进行分析，提供具体的科学依据和建议。");

            System.out.println("构建的AI分析提示词长度: " + prompt.length());

            // 调用AI服务
            Map<String, Object> aiParameters = new HashMap<>();
            aiParameters.put("prompt", prompt.toString());
            aiParameters.put("factories", nearbyFactories);
            aiParameters.put("location", Map.of("latitude", latitude, "longitude", longitude));

            String aiResult = aiService.generalAnalysis("factory_environmental_impact", aiParameters);

            if (aiResult == null || aiResult.trim().isEmpty()) {
                System.out.println("AI服务返回空结果，使用备用分析方法");
                return generateFallbackFactoryAnalysis(nearbyFactories);
            }

            System.out.println("AI分析完成，结果长度: " + aiResult.length());
            return aiResult;

        } catch (Exception e) {
            System.err.println("调用AI服务失败: " + e.getMessage());
            e.printStackTrace();
            return generateFallbackFactoryAnalysis(nearbyFactories);
        }
    }

    /**
     * 生成备用化工厂分析（当AI服务不可用时）
     */
    private String generateFallbackFactoryAnalysis(List<Map<String, Object>> nearbyFactories) {
        StringBuilder analysis = new StringBuilder();
        analysis.append("=== 化工厂环境影响分析报告 ===\n\n");

        // 按风险等级统计
        long highRiskCount = nearbyFactories.stream().filter(f -> "high".equals(f.get("riskLevel"))).count();
        long mediumRiskCount = nearbyFactories.stream().filter(f -> "medium".equals(f.get("riskLevel"))).count();

        analysis.append("分析概况：发现 ").append(nearbyFactories.size()).append(" 家化工厂\n");
        analysis.append("- 高风险工厂：").append(highRiskCount).append(" 家\n");
        analysis.append("- 中等风险工厂：").append(mediumRiskCount).append(" 家\n");
        analysis.append("- 低风险工厂：").append(nearbyFactories.size() - highRiskCount - mediumRiskCount).append(" 家\n\n");

        // 详细分析每个工厂
        for (Map<String, Object> factory : nearbyFactories) {
            String name = (String) factory.get("name");
            Double distance = (Double) factory.get("distance");
            String industry = (String) factory.get("industry");
            String pollutants = (String) factory.get("mainPollutants");
            String riskLevel = (String) factory.get("riskLevel");

            analysis.append("🏭 ").append(name).append("\n");
            analysis.append("   距离：").append(distance).append("km\n");
            analysis.append("   行业：").append(industry).append("\n");
            analysis.append("   主要污染物：").append(pollutants).append("\n");
            analysis.append("   风险等级：").append(riskLevel).append("\n");

            // 风险分析
            if (distance <= 2.0) {
                analysis.append("   ⚠️ 近距离高风险，可能对监测点造成直接影响\n");
            } else if (distance <= 5.0) {
                analysis.append("   ⚠️ 中等距离，需要重点监测污染物扩散\n");
            } else {
                analysis.append("   ✅ 距离较远，风险相对较低\n");
            }

            // 污染物分析
            if (pollutants != null) {
                if (pollutants.contains("重金属")) {
                    analysis.append("   🔴 重金属污染物：具有生物累积性，长期风险高\n");
                }
                if (pollutants.contains("有机物") || pollutants.contains("COD")) {
                    analysis.append("   🟡 有机污染物：可能导致水体富营养化\n");
                }
                if (pollutants.contains("酸") || pollutants.contains("碱")) {
                    analysis.append("   🟠 酸碱污染物：会改变水体pH值，影响生态平衡\n");
                }
            }

            analysis.append("\n");
        }

        // 总体建议
        analysis.append("=== 总体环境风险评估 ===\n");
        if (highRiskCount > 0) {
            analysis.append("🚨 高风险：发现高风险化工厂，建议加强监测\n");
            analysis.append("   - 增加监测频率至每小时一次\n");
            analysis.append("   - 建立污染物扩散监测网络\n");
            analysis.append("   - 制定详细的应急响应预案\n");
        } else if (mediumRiskCount > 0) {
            analysis.append("⚠️ 中等风险：存在中等风险工厂，需要持续关注\n");
            analysis.append("   - 保持常规监测频率\n");
            analysis.append("   - 定期评估污染物扩散趋势\n");
            analysis.append("   - 与化工厂建立信息共享机制\n");
        } else {
            analysis.append("✅ 低风险：整体风险较低，建议常规监测\n");
            analysis.append("   - 保持日常监测频率\n");
            analysis.append("   - 定期检查设备运行状态\n");
            analysis.append("   - 建立长期环境监测档案\n");
        }

        return analysis.toString();
    }

    /**
     * 获取设备列表（用于前端显示）
     * GET /device-pollution-prediction/device-list
     */
    @GetMapping("/device-list")
    public ResultVo getDeviceList() {
        try {
            System.out.println("开始获取设备列表");

            // 这里应该从数据库获取设备信息
            // 由于暂时没有设备管理的service，先返回模拟数据
            // 在实际项目中应该调用设备管理的service

            List<Map<String, Object>> deviceList = new ArrayList<>();

            // 模拟设备数据（实际应该从数据库获取）
            deviceList.add(createDeviceInfo(1L, "监测点001", 38.814788, 115.489120, "online", 7.12, 28.0, 0));
            deviceList.add(createDeviceInfo(2L, "监测点002", 38.814788, 116.357428, "online", 7.2, 22.5, 1200));
            deviceList.add(createDeviceInfo(3L, "监测点003", 39.92923, 116.437428, "online", 6.8, 24.2, 1800));
            deviceList.add(createDeviceInfo(4L, "监测点004", 39.88923, 116.317428, "online", 7.5, 21.3, 900));
            deviceList.add(createDeviceInfo(5L, "监测点005", 39.86923, 116.277428, "online", 6.9, 23.7, 1500));
            deviceList.add(createDeviceInfo(6L, "监测点006", 39.91323, 116.195428, "online", 7.3, 22.1, 1100));
            deviceList.add(createDeviceInfo(7L, "监测点007", 39.90923, 116.661428, "online", 7.1, 23.8, 1600));
            deviceList.add(createDeviceInfo(8L, "监测点008", 40.22423, 116.235428, "online", 6.7, 25.1, 2000));

            Map<String, Object> result = new HashMap<>();
            result.put("devices", deviceList);
            result.put("totalCount", deviceList.size());
            result.put("timestamp", System.currentTimeMillis());

            System.out.println("设备列表获取完成，共 " + deviceList.size() + " 个设备");
            return ResultVo.success(result);

        } catch (Exception e) {
            System.err.println("获取设备列表失败: " + e.getMessage());
            e.printStackTrace();
            return ResultVo.error(ApiServiceExceptionEnum.RESULT_ERROR);
        }
    }

    /**
     * 创建设备信息对象
     */
    private Map<String, Object> createDeviceInfo(Long deviceId, String deviceName, Double latitude, Double longitude,
                                                String status, Double ph, Double temp, Integer ntu) {
        Map<String, Object> device = new HashMap<>();
        device.put("id", deviceId);
        device.put("name", deviceName);
        device.put("location", "待获取地址"); // 实际应该从数据库获取
        device.put("latitude", latitude);
        device.put("longitude", longitude);
        device.put("status", status);
        device.put("ph", ph);
        device.put("temp", temp);
        device.put("ntu", ntu);
        return device;
    }

}
